import axios from 'axios'
import { Loading } from 'element-ui'
import qs from 'qs'
import { JSEncrypt } from 'jsencrypt'
// import Vue from 'vue'
const AxiosParam = {
  urlPre: '',
  headerPre: {
    token: '',
  },
  baseURL: '',
}
let loadingInstance = null
let loadingCount = 0
let loadingTxt = '努力获取中'
const noLoad = {}
let Axios = null
Axios = axiosInit()

const key = `MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAngjk/aRDZCzrmrAPBc7l149I3etjRnMsN0CbyvdDiU4CS97Fm+nCZYcgQoKGkQA/N4+/saDWbKSJXfUULY4gKwIDAQABAkAWLNFU9fOu3s7AievRuNJviN+EpD7t58NQjXRO6ptDbMDm9C189wnVvBlGqvqW81qXp4AG1nMDWA2uji2buNHBAiEA/EO9q+6nQH83SzDEkJedFcUZm3YUGG6Nw/RZsFMOl3MCIQCgX/ThhfAHR1uNR/a3OpYB1UjUcF+Xv6Virm1JE3F2aQIhAL11EspB3pLt+FUcN0Rw2aUz9ltvfwAqZ4Y3yfRHLLpJAiAJzPNlGM9LUpQItT4hgmYKZKNXwCpHVsHfnvM0xQhpCQIgQdRnJtumxXQBgZZP2HxGHdkUHQvcKO9l1DpDwGTEQR4=`

export function RSAencode(str) {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey(key)
  return encrypt.encrypt(str)
}
export function RSAdecode(str) {
  const decrypt = new JSEncrypt()
  decrypt.setPublicKey(key)
  return decrypt.decrypt(str)
}
// 初始化系统公共函数
export function initGlobalFunc(content) {
  // console.log(Vue.prototype)
  window.$t = content.$t.bind(content)
  window.$set = content.$set.bind(content)
  window.$message = {
    success: str => {
      content.$message.success(str.toString())
    },
    error: error => {
      content.$message.error(error.toString())
    },
    warning: warn => {
      content.$message.warning(warn.toString())
    },
  }
  window.$getStore = key => {
    return content.$store.state[key]
  }
  window.$setStore = (key, param) => {
    content.$store.state[key] = param
  }
  window.$rPush = param => {
    let rt = content.$router
    // param.query = { page: param.name }
    rt.push(param)
  }
  window.$rReplace = param => {
    let rt = content.$router
    // let par = { name:param.name, query: {} }
    // Object.assign(par.query, param.query)
    rt.replace(param)
  }
}

// 将文本插入到剪切板
export function inClipboard(text, hits = '已复制到剪切板') {
  try {
    // 创建元素用于复制
    const aux = document.createElement('input')
    // 设置元素内容
    aux.setAttribute('value', text)
    // 将元素插入页面进行调用
    document.body.appendChild(aux)
    // 复制内容
    aux.select()
    // 将内容复制到剪贴板
    document.execCommand('copy')
    // 删除创建元素
    document.body.removeChild(aux)
    $message.success(hits)
  } catch (error) {
    $message.error('不支持剪切板')
  }
}

// 通过Canvas测任意字符串宽度
export function getTextWidth(text, font = 'normal 12px arial') {
  var canvas =
    getTextWidth.canvas || (getTextWidth.canvas = document.createElement('canvas'))
  var context = canvas.getContext('2d')
  context.font = font
  var metrics = context.measureText(text)
  return metrics.width
}

// 动态创建script加载js
export function importJs(url) {
  return new Promise(resolve => {
    const script = document.createElement('script')
    script.src = url
    script.onload = function () {
      resolve()
    }
    document.body.appendChild(script)
  })
}

// 动态创建script加载css
export function importCss(url) {
  let new_element = document.createElement('link')
  new_element.setAttribute('rel', 'stylesheet')
  new_element.setAttribute('href', url)
  document.body.appendChild(new_element)
}

//关闭当前浏览器页签
export function closeCurrentWindow() {
  window.open(location, '_self').close()
}

export function getCookie(key) {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(key + '=')
    if (c_start != -1) {
      c_start = c_start + key.length + 1
      let c_end = document.cookie.indexOf(';', c_start)
      if (c_end == -1) c_end = document.cookie.length
      return unescape(document.cookie.substring(c_start, c_end))
    }
  }
  return ''
}

export function copyPath(str) {
  let oInput = document.createElement('input')
  oInput.value = str
  document.body.appendChild(oInput)
  oInput.select() // 选择对象;
  console.log(oInput.value)
  document.execCommand('Copy') // 执行浏览器复制命令
  $message.success('复制成功')
  oInput.remove()
}

export function isEmpty(obj) {
  return (
    obj === undefined ||
    obj === null ||
    obj === '' ||
    (Array.isArray(obj) && obj.length === 0) ||
    JSON.stringify(obj) === '{}'
  )
}

export function openNew(router, param) {
  const text = router.resolve(param)
  window.open(text.href, '_blank')
}

export function download(stream, fileNanme, disposition, type = 'application/zip') {
  const aTag = document.createElement('a')
  aTag.href = URL.createObjectURL(new Blob([stream], { type }))
  aTag.download = fileNanme //fileName自定义
  aTag.click()
  URL.revokeObjectURL(aTag.href) //释放通过URL.createObjectURL()创建的对象URL
  // $message.success('导出成功')
}

export function toThousands(num) {
  // return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
  if (isEmpty(num)) {
    return '-'
  }
  if (typeof num == 'number' && num > 100000000) {
    return (num / 100000000).toFixed(2) + '亿'
  }
  return num
}

export function formatBytes(a, b) {
  if (0 == a) return '0 Bytes'
  var c = 1024,
    d = b || 2,
    e = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    f = Math.floor(Math.log(a) / Math.log(c))
  return parseFloat((a / Math.pow(c, f)).toFixed(d)) + e[f]
}

export function axiosGet(url, params = {}) {
  return Axios.get(`${AxiosParam.urlPre}${url}`, { params })
}
export function axiosPost(
  url,
  params = {},
  content_type = 'application/json;charset=UTF-8',
) {
  if (content_type === 'application/x-www-form-urlencoded') {
    return Axios.post(`${AxiosParam.urlPre}${url}`, qs.stringify(params))
  } else if (content_type === 'multipart/form-data') {
    const tmp = new FormData()
    Object.keys(params).forEach(key => {
      tmp.append(key, params[key])
    })
    loadingTxt = '努力上传中'
    return Axios.post(`${AxiosParam.urlPre}${url}`, tmp, { timeout: 0 })
  } else if (content_type === 'application/json;application/octet-stream') {
    return Axios.post(`${AxiosParam.urlPre}${url}`, params, {
      responseType: 'arraybuffer',
      timeout: 0,
    })
  }
  return Axios.post(`${AxiosParam.urlPre}${url}`, params)
}
export function axiosPut(url, params) {
  return Axios.put(`${AxiosParam.urlPre}${url}`, params)
}
export function axiosDelete(url, params) {
  return Axios.delete(
    `${AxiosParam.urlPre}${url}?${qs.stringify(params, { indices: false })}`,
  )
}
export function axiosDelete2(url, params) {
  return Axios.delete(`${AxiosParam.urlPre}${url}`, { params })
}
export function axiosDeleteBody(url, data) {
  return Axios.delete(`${AxiosParam.urlPre}${url}`, { data })
}
export function axiosAll(axiosArr, callback, error, end) {
  return axios
    .all(axiosArr)
    .then(axios.spread(callback))
    .catch(error => {
      $message.error(error)
    })
    .finally(() => {
      end && end()
    })
}

function loadStart() {
  loadingCount++
  if (loadingInstance === null) {
    loadingInstance = Loading.service({
      fullscreen: true,
      text: loadingTxt,
      spinner: 'el-icon-loading',
    })
  }
}

function loadEnd() {
  if (loadingInstance !== null && --loadingCount === 0) {
    loadingInstance.close()
    loadingInstance = null
    loadingTxt = '努力获取中'
  }
}

function axiosInit() {
  if (Axios) {
    return Axios
  }
  const instance = axios.create({
    headers: AxiosParam.headerPre,
    timeout: 60000,
    baseURL: AxiosParam.baseURL,
  })
  instance.interceptors.request.use(
    config => {
      config.headers.token = getCookie('token')
      let re = config.url.match(/\[.*?\]/g)
      if (re !== null) {
        for (let item of re) {
          let tmp = item.replace('[', '').replace(']', '')
          config.url = config.url.replace(item, config.params[tmp])
        }
      }
      noLoad[config.url] = false
      if (config.params && config.params.noLoad === true) {
        noLoad[config.url] = true
      }
      if (config.data && config.data.noLoad === true) {
        noLoad[config.url] = true
      }
      if (!noLoad[config.url]) {
        loadStart()
      }
      return config
    },
    error => {
      !noLoad[error.config.url] && loadEnd()
      return Promise.reject('网络异常')
    },
  )
  instance.interceptors.response.use(
    res => {
      !noLoad[res.config.url] && loadEnd()
      if (
        res.headers['content-type'] &&
        res.headers['content-type'].indexOf('application/octet-stream') !== -1
      ) {
        return Promise.resolve(res)
      }
      if (res.data.status === 0) {
        //数资逻辑
        return Promise.resolve(res.data)
      }
      if (res.data.code === '200') {
        //UC逻辑
        return Promise.resolve(res.data)
      }
      if (res.data.errorCode) {
        //数资逻辑
        switch (res.data.errorCode) {
          case 10019:
            // top.location.href = '/logout'
            // $rReplace({ name: 'login' })
            return Promise.reject('请重新登陆')
          case 20010:
            return Promise.reject(res.data.cause || 'cause:未找到')
        }
      }
      if (res.data.code) {
        //UC逻辑
        switch (res.data.code) {
          case '702':
            // top.location.href = '/logout'
            // $rReplace({ name: 'login' })
            return Promise.reject(res.data.msg)
        }
      }
      return Promise.reject(res.data.error || 'error:未找到')
    },
    error => {
      !noLoad[error.config.url] && loadEnd()
      if (error.message && error.message.indexOf('404') > -1) {
        return Promise.reject('请求的资源未找到')
      } else if (
        error.message &&
        (error.message.indexOf('502') > -1 || error.message.indexOf('500') > -1)
      ) {
        return Promise.reject('请求的服务出错')
      } else if (error.message && error.message.indexOf('401') > -1) {
        // top.location.href = '/logout'
        // $rReplace({ name: 'login' })
        return Promise.reject('请重新登陆')
      } else if (error.message && error.message.indexOf('timeout') > -1) {
        return Promise.reject('请求超时，请检查网络')
      }
      let re =
        (error.message && error.message.toString()) ||
        (error.msg && error.msg.toString()) ||
        'message:未找到'
      return Promise.reject(re)
    },
  )
  return instance
}

Object.defineProperty(Array.prototype, 'clearAll', {
  enumerable: false,
  value: function () {
    if (Array.isArray(this)) {
      this.length = 0
      this.reverse()
      // this.splice(0, this.length - 1)
    }
  },
})

//数组按照key去除重复项目，改变原始数组
Object.defineProperty(Array.prototype, 'clearRepeat', {
  enumerable: false,
  value: function (key) {
    if (Array.isArray(this)) {
      let tmp = {}
      this.forEach(i => {
        //重复的保留后面的
        tmp[i[key]] = i
      })
      this.clearAll()
      Object.values(tmp).forEach(i => {
        this.push(i)
      })
    }
  },
})
Object.defineProperty(Array.prototype, 'delete', {
  enumerable: false,
  value: function (item) {
    if (Array.isArray(this)) {
      let tmp = []
      this.forEach(i => {
        if (i !== item) {
          tmp.push(i)
        }
      })
      this.clearAll()
      tmp.forEach(i => {
        this.push(i)
      })
    }
  },
})
Object.defineProperty(Array.prototype, 'contain', {
  enumerable: false,
  value: function (obj, key) {
    if (Array.isArray(this)) {
      for (const iterator of this) {
        if (obj[key] === iterator[key]) {
          return true
        }
      }
    }
    return false
  },
})

window.$ajax = {
  get: axiosGet,
  put: axiosPut,
  post: axiosPost,
  delete: axiosDelete2,
  deleteBody: axiosDeleteBody,
}
window.$qs = qs
window.$isEmpty = isEmpty
window.$RSAencode = RSAencode
window.$RSAdecode = RSAdecode

window.ajax = {
  get: axiosGet,
  put: axiosPut,
  post: axiosPost,
  delete: axiosDelete2,
  deleteBody: axiosDeleteBody,
}
window.isEmpty = isEmpty
window.RSAencode = RSAencode
window.RSAdecode = RSAdecode
